/*************************************************************************
	> File Name: 002.Expandable_SequenceList.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 三  9/ 1 15:32:55 2021
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define COLOR(a, b) "\033[" #b "m" a "\033[0m"
#define GREEN(a) COLOR(a, 32)

typedef struct Vector {
    int *data;
    int size;
    int length;
} Vec;

/*
 * 顺序表的初始化
 */
Vec *init(int n) {
    Vec *v = (Vec *)malloc(sizeof(Vec));
    v->data = (int *)malloc(sizeof(int) * n);
    v->size = n;
    v->length = 0;
    return v;
}

/*
 * 顺序表的扩展
 */
int expand(Vec *v) {
    int extr_size = v->size;
    int *p; //防止内存泄漏，定义指针变量保存新的地址
    while (extr_size) {
        p = (int *)realloc(v->data, sizeof(int) * (v->size + extr_size)); //对v->data指向的空间进行扩容
        if (p) break; //p为空，说明空间realloc失败
        extr_size /= 2; //尝试开辟的空间大小失败，于是尝试开辟一半
    }
    if (extr_size == 0) //开辟失败
        return 0;
    v->data = p; //将新开辟的空间地址赋给v->data
    v->size += extr_size;
    return 1;
}

/*
 * 顺序表的插入
 */
int insert(Vec *v, int val, int ind) {
    if (v == NULL) 
        return 0;
    if (ind < 0 || ind > v->length) 
        return 0;
    if (v->length == v->size) { //存储的元素已经到达最大容量
        if (!expand(v)) 
            return 0;
        printf(GREEN("Success to expand! The vector size is %d") "\n", v->size);
    }
    for (int i = v->length; i > ind; i--) {
        v->data[i] = v->data[i - 1];
    }
    v->data[ind] = val;
    v->length++;
    return 1;
}

/*
 * 顺序表的删除
 */
int erase(Vec *v, int ind) {
    if (v == NULL) return 0;
    if (ind < 0 || ind >= v->length) return 0;
    for (int i = ind + 1; i < v->length; i++) {
        v->data[i - 1] = v->data[i];
    }
    v->length--;
    return 1;
}


/*
 * 顺序表的销毁
 */
void clear(Vec *v) {
    if (v == NULL) return ;
    free(v->data);
    free(v);
    return ;
}

/*
 * 顺序表的输出
 */
void output(Vec *v) {
    if (v == NULL) return ;
    printf("Vector : [");
    for (int i = 0; i < v->length; i++) {
        i && printf(", ");
        printf("%d", v->data[i]);
    }
    printf("]\n");
    return ;
}

int main() {
    srand(time(0));
    #define max_op 20 
    Vec *vec = init(5);
    for (int i = 0; i < max_op; i++) {
        int val = rand() % 100;
        int ind = rand() % (vec->length + 3) - 1;
        int op = rand() % 4;
        switch (op) {
            case 0:
            case 1:
            case 2: {
                printf("insert %d at %d to Vector, result = %d\n", val, ind, insert(vec, val, ind));
            } break;
            case 3: {
                printf("erase an item at %d from Vector, result = %d\n", ind, erase(vec, ind));
            } break;
        }
        output(vec);
        printf("\n");
    }
    clear(vec);
    #undef max_op
    return 0;
}
